package com.lgmshare.component.widget.recyclerview;

import android.content.Context;
import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

/**
 * @author lim
 * @description: TODO
 * @email lgmshare@gmail.com
 * @datetime 2018/2/7 17:30
 */
public class StaggeredGridItemDecoration extends RecyclerView.ItemDecoration {

    private int mSpanCount;
    private int mSpace;
    private int mHeaderCount;
    private int mFooterCount;
    private boolean mIncludeEdge;

    public StaggeredGridItemDecoration(Context context, int spanCount, int space, boolean includeEdge) {
        this(context, spanCount, space, 0, includeEdge);
    }

    public StaggeredGridItemDecoration(Context context, int spanCount, int space, int headerCount, boolean includeEdge) {
        this(context, spanCount, space, headerCount, 0, includeEdge);
    }

    public StaggeredGridItemDecoration(Context context, int spanCount, int space, int headerCount, int footerCount, boolean includeEdge) {
        this.mSpanCount = spanCount;
        this.mSpace = dipToPx(context, space);
        this.mIncludeEdge = includeEdge;
        this.mHeaderCount = headerCount;
        this.mFooterCount = footerCount;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position
        if (position < mHeaderCount) {
            return;
        }
        int itemCount = parent.getAdapter().getItemCount();
        if (itemCount - position <= mFooterCount) {
            return;
        }
        StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
        int spanIndex = layoutParams.getSpanIndex();
        if (mIncludeEdge) {
            outRect.left = mSpace - spanIndex * mSpace / mSpanCount; // mSpace - column * ((1f / mSpanCount) * mSpace)
            outRect.right = (spanIndex + 1) * mSpace / mSpanCount; // (column + 1) * ((1f / mSpanCount) * mSpace)
            if (position - mHeaderCount < mSpanCount) {
                outRect.top = mSpace;
            }
            outRect.bottom = mSpace;
        } else {
            outRect.left = spanIndex * mSpace / mSpanCount; // column * ((1f / mSpanCount) * mSpace)
            outRect.right = mSpace - (spanIndex + 1) * mSpace / mSpanCount; // mSpace - (column + 1) * ((1f /    mSpanCount) * mSpace)
            if (position - mHeaderCount > mSpanCount) {
                outRect.top = mSpace;
            }
        }
    }

    private int dipToPx(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
